#include <klib.h>
#include <klib-macros.h>
#include <stdint.h>

#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)

size_t strlen(const char *s) {

  size_t num = 0;
  while (*s++ != '\0') {
    num++;
  }
  return num;
  //panic("Not implemented");
}

//用于将源字符串（src）的内容复制到目标字符串（dst）
char *strcpy(char *dst, const char *src) {
  assert(dst && src);
	char *ptr = dst; // 保存目标字符串起始地址

  // 逐个复制源字符串的字符到目标字符串，直到遇到字符串结束符 \0
  while (*src != '\0') {
    *dst++ = *src++;
  }
  *dst = '\0'; // 添加目标字符串的结束符 \0

  return ptr; // 返回目标字符串的起始地址
  //panic("Not implemented");
}

char *strncpy(char *dst, const char *src, size_t n) {
  panic("Not implemented");
}

char *strcat(char *dst, const char *src) {
  assert(dst != NULL && src != NULL);
  char* temp=dst;// 保存目标字符串起始地址
  // 找到目标字符串的末尾
  while (*dst != '\0') {
    dst++;
  }
  // 复制源字符串的内容到目标字符串末尾
  while (*src != '\0') {
    *dst++ = *src++;
  }
  // 添加新的'\0'字符以结束新字符串
  *dst = '\0';

  return temp;
  //panic("Not implemented");
}

int strcmp(const char *s1, const char *s2) {
  while(*s1==*s2 && *s1 != '\0' && *s2 != '\0'){
		s1++;
		s2++;
	}
	return *s1-*s2;

  //panic("Not implemented");
}

int strncmp(const char *s1, const char *s2, size_t n) {
  panic("Not implemented");
}

//用于将指定内存区域的前 n 个字节设置为特定的值
void *memset(void *s, int c, size_t n) {
  unsigned char *p = (unsigned char *)s;
  unsigned char value = (unsigned char)c;

  for (size_t i = 0; i < n; i++) {
    *p++ = value;
  }

  return s;
  //panic("Not implemented");
}

void *memmove(void *dst, const void *src, size_t n) {
  panic("Not implemented");
}

//用于将源内存区域的内容复制到目标内存区域
void *memcpy(void *out, const void *in, size_t n) {

  unsigned char *dest = (unsigned char *)out;
  const unsigned char *src = (const unsigned char *)in;

  for (size_t i = 0; i < n; i++) {
    dest[i] = src[i];
  }

  return out;
  //panic("Not implemented");
}

//用于比较两个内存区域的内容是否相等
int memcmp(const void *s1, const void *s2, size_t n) {
  const unsigned char *p1 = (const unsigned char *)s1;
  const unsigned char *p2 = (const unsigned char *)s2;

  for (size_t i = 0; i < n; i++) {
    if (p1[i] != p2[i]) {
      return p1[i] - p2[i];
    }
  }

  return 0;
  //panic("Not implemented");
}

#endif
